package com.john.seckill.exception;

import com.john.seckill.vo.ResultBean;
import com.john.seckill.vo.ResultBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 * 日期 2021/5/19 20:09
 * 创建者：john
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResultBean handlerException(Exception e){ // 1.自定义异常的处理
        log.info(String.valueOf(e));
        if(e instanceof GlobalException){
            GlobalException ex = (GlobalException)e;
            return ResultBean.error(ex.getResultBeanEnum());
        }else if(e instanceof BindException){   // 2.@Valid 抛出异常的处理
            BindException ex = (BindException)e;
            final ResultBean resultBean = ResultBean.error(ResultBeanEnum.BIND_ERROR);
            resultBean.setMessage("参数校验异常："+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return resultBean;
        }
        return ResultBean.error(ResultBeanEnum.ERROR); // 3.其他异常的处理
    }
}
